﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;

namespace _3DTicTacToe.UI
{
    partial class LogViewWindow : Window
    {
        private string[] _flags;
        private readonly Queue<LogEntry> _pendingEntries;
        private readonly Timer _timer;

        public LogViewWindow()
        {
            InitializeComponent();
            _pendingEntries = new Queue<LogEntry>();
            _timer = new Timer(200);
            _timer.Elapsed += delegate { Dispatcher.Invoke(new Action(ProcessPendingEntries)); };
            _timer.Enabled = true;

            Log.OnLogEntry += NetLog_OnLogEntry;

            logTextBox.Text = Log.GetLogString();
            logTextBox.ScrollToEnd();
        }

        void ProcessPendingEntries()
        {
            while(_pendingEntries.Count > 0)
            {
                var newEntry = _pendingEntries.Dequeue();

                if (_flags != null && !newEntry.Flags.All(n => _flags.Contains(n)))
                    return;

                logTextBox.Text += Log.GetString(newEntry) + Environment.NewLine;
                logTextBox.ScrollToEnd();
            } 
        }

        void NetLog_OnLogEntry(LogEntry newEntry)
        {
            _pendingEntries.Enqueue(newEntry);
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            Log.OnLogEntry -= NetLog_OnLogEntry;
        }

        private void filterTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (filterTextBox.Text.Length > 0)
            {
                _flags = filterTextBox.Text.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries).ToArray();
                var entries = Log.Filter(_flags);

                logTextBox.Text = Log.GetLogString(entries);
            }
            else
            {
                _flags = null;
                logTextBox.Text = Log.GetLogString();
                logTextBox.ScrollToEnd();
            }  
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var d = DateTime.Now;
            var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                                        string.Format("3dtictactoe-log-{0}-{1}-{2}_{3}-{4}-{5}.txt", d.Year, d.Month, d.Day,
                                                      d.Hour, d.Minute, d.Second));
            File.WriteAllText(filename, logTextBox.Text);
        }
    }
}